#include <iostream>
#include "TcpServer.hpp"
#include "Protocol.hpp"
#include "Calculator.hpp"
#include <functional>
using namespace LockModule;
using cal_fun = std::function<response(const request &req)>;
class parse
{
public:
    parse(cal_fun cal) : _cal(cal) {}
    std::string entry(std::string &package)
    {
        std::string content;
        std::string message;
        // 判断完整性+提取报文
        while (Decode(package, &content))
        {
            LOG(LogLevel::DEBUG) << "Content: \n" << message;
            if (content.empty())
                break;
            // 反序列化
            request req;
            if (!req.deserialization(content))
                break;

            std::cout << "#############" << std::endl;
            req.print();
            std::cout << "#############" << std::endl;
            // 计算模块处理

            response resp = _cal(req);
            // 序列化
            std::string str;
            if (!resp.Serialization(str))
                break;

            LOG(LogLevel::DEBUG) << "序列化: \n" << str;

            // 添加长度报头字段
            Encode(str);
             LOG(LogLevel::DEBUG) << "Encode: \n" << str;
            message += str;
        }

        // 返回报文
        LOG(LogLevel::DEBUG) << "respstr: \n" << message;
        return message;
    }

private:
    cal_fun _cal;
};

int main()
{
    ENABLE_CONSOLE_LOG();
    // 计算模块
    Calculator cal;
    // 解析模块
    parse cmd([&cal](const request &req)
              { return cal.classify(req); });
    // 通信模块
    std::unique_ptr<TcpServer> tcp_ser = std::make_unique<TcpServer>([&cmd](std::string &package)
                                                                     { return cmd.entry(package); });
    tcp_ser->InitServer();
    tcp_ser->Start();
    return 0;
}